import { defineStore } from 'pinia'
import router, { constantRoutes } from '@/router'
import { transformAsyncRoutes } from '@/router/modules/transformRoutes'
import type { RouteRecordRaw } from 'vue-router'
import { reqmenuList } from '@/api/menu/menu'

interface PermissionState {
  routes: RouteRecordRaw[]
  addRoutes: RouteRecordRaw[]
  isRoutesLoaded: boolean
}

export const usePermissionStore = defineStore('permission', {
  state: (): PermissionState => ({
    routes: [],
    addRoutes: [],
    isRoutesLoaded: false,
  }),

  actions: {
    async loadBackendRoutes() {
      const res = await reqmenuList()
      const accessedRoutes = transformAsyncRoutes(res.data)
      console.log('菜单路由。。。。', res.data)
      accessedRoutes.forEach((route: RouteRecordRaw) => {
        router.addRoute(route)
      })

      this.addRoutes = accessedRoutes
      this.routes = [...accessedRoutes, ...constantRoutes]
      this.isRoutesLoaded = true
    },
  },
})
